package org.p2psimulator.entity.protocol.structured.chordcycles;

import java.util.List;
import org.p2psimulator.engine.Environment;
import org.p2psimulator.entity.Id;
import org.p2psimulator.entity.Message;
import org.p2psimulator.entity.Peer;
import org.p2psimulator.entity.overlaynetwork.routingtable.ChordFingerTable;
import org.p2psimulator.entity.protocol.messages.MessageTypes;
import org.p2psimulator.entity.protocol.messages.chord.AreYouAlive;

public class ChordFixSucessorCycle extends ChordCycle {

	public ChordFixSucessorCycle(Environment env, int transId) {
		super(env, transId);

	}

	@Override
	public String runRequestCycle(Peer p) {
		StringBuilder str = new StringBuilder("  [FIX SUCESSOR CYCLE]   -   ");

		ChordFingerTable table = getFingerTable(p);
		AreYouAlive areYouAlive = new AreYouAlive(p.getId(), table
				.getSucessor(), currentTransactionId, p.getBehavior()
				.getBehaviorType());

		areYouAlive.setServentId(p.getId());
		areYouAlive.setTTL(255);
		areYouAlive.setHOP(0);

		env.getNetwork().sendMessage(areYouAlive);

		str.append("[AREYOUALIVE SENT]");
		return str.toString();
	}

	@Override
	public String runResponseCycle(Peer p) {
		StringBuilder str = new StringBuilder("  [FIX FINGERS CYCLE]   -  ");

		ChordFingerTable table = getFingerTable(p);
		List<Message> sucessorList = p.getMessageStack().get(
				MessageTypes.CHORD_IAMALIVE.getName());
		if (sucessorList != null & sucessorList.size() > 0) {

			Id sucessor = sucessorList.get(0).getServentId();
			str.append("[IAMALIVE RECEBIDA]");

			Double mySucValue = (Double) table.getSucessor().getValue();
			Double sucValue = (Double) sucessor.getValue();
			if (sucValue == mySucValue) {
				str.append(" [SUCESSOR ONLINE (ok)]");
				return str.toString();
			} else {
				table.setSucessorOnline(false);
				str
						.append("[ Error: IamAlive recebida não corresponde ao sucessor atual,"
								+ "provável erro no roteamento]");
				return str.toString();
			}
		} else {
			table.setSucessorOnline(false);
			str
					.append("[nenhuma resposta recebida. Sucessor provavelmente offline]");
		}

		return str.toString();
	}

	@Override
	public String runSecondRequestCycle(Peer p) {
		return "";
	}

	@Override
	public String runSecondResponseCycle(Peer p) {
		return "";
	}

}
